import db from "../connector/db";
import log from "../log";
import { UserPassword } from "@prisma/client";
import * as argon2 from "argon2";
import AppError from "@/shared/app-error";

const encrypte = async (password: string): Promise<string> => {
  try {
    return await argon2.hash(password, { type: argon2.argon2id });
  } catch (err) {
    log.error("加密密码失败", err);
    throw AppError.unhandledError("加密密码失败");
  }
};

const check = async (password: string, encryptedPassword: string): Promise<boolean> => {
  try {
    return await argon2.verify(encryptedPassword, password);
  } catch (err) {
    log.error("匹配密码失败", err);
    throw AppError.unhandledError("匹配密码失败");
  }
};

const findByUserId = async (userId: string): Promise<UserPassword | null> => {
  return await db.userPassword.findFirst({ where: { userId } });
};

const userPasswordService = {
  encrypte,
  check,
  findByUserId,
};

export default userPasswordService;
